package com.richbond.sdjdsm.fragments;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.idcard.CardInfo;
import com.idcard.TFieldID;
import com.idcard.TengineID;
import com.richbond.sdjdsm.MainActivity;
import com.richbond.sdjdsm.R;
import com.richbond.sdjdsm.ShowPicActivity;
import com.richbond.sdjdsm.UserLoginActivity;
import com.richbond.sdjdsm.bean.CustomBean;
import com.richbond.sdjdsm.bean.HwlxBean;
import com.richbond.sdjdsm.bean.OrderBean;
import com.richbond.sdjdsm.bean.UpdateBean;
import com.richbond.sdjdsm.common.BaseFragment;
import com.richbond.sdjdsm.dao.CustomDao;
import com.richbond.sdjdsm.dao.GoodsTypeDao;
import com.richbond.sdjdsm.dao.OrderDao;
import com.richbond.sdjdsm.sharedpreferences.HwlxSharedPreferences;
import com.richbond.sdjdsm.sharedpreferences.UserSharedPreferences;
import com.richbond.sdjdsm.util.CropParams;
import com.richbond.sdjdsm.util.DialogHelper;
import com.richbond.sdjdsm.util.ImageUtil;
import com.richbond.sdjdsm.util.JsonUtil;
import com.richbond.sdjdsm.util.StringUtils;
import com.richbond.sdjdsm.util.SystemUtil;
import com.richbond.sdjdsm.util.UIHelp;
import com.richbond.sdjdsm.util.update.UpdateManager;
import com.richbond.sdjdsm.webserver.PoiWS;
import com.richbond.sdjdsm.widget.wheel.OnWheelChangedListener;
import com.richbond.sdjdsm.widget.wheel.WheelView;
import com.richbond.sdjdsm.widget.wheel.adapters.ArrayWheelAdapter;
import com.richbond.sdjdsm.wintone.CameraActivity;
import com.richbond.sdjdsm.wintone.SharedPreferencesHelper;
import com.ui.card.TRCardScan;

import org.jivesoftware.smack.util.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wintone.idcard.android.AuthService;
import zxing.activity.CaptureActivity;

/**
 * 主界面：首页
 */
public class HomeFragment extends BaseFragment implements AMapLocationListener, Runnable, OnWheelChangedListener {
    public static final String TAG = HomeFragment.class.getSimpleName();
    @Bind(R.id.et_number)
    EditText et_number;//单号
    @Bind(R.id.etPhone)
    EditText etPhone;//寄件人电话
    @Bind(R.id.etName)
    EditText etName;//寄件人姓名
    @Bind(R.id.etIdCard)
    EditText etIdCard;//寄件人身份证号码
    @Bind(R.id.etRPhone)
    EditText etRPhone;//收件人电话
    @Bind(R.id.tv_ssx)
    TextView tv_ssx;//到货地址：省市县
    @Bind(R.id.et_details_address)
    EditText et_details_address;//详细到货地址
    @Bind(R.id.ck_kxys)
    CheckBox ck_kxys;//开箱验视
    @Bind(R.id.ck_wxp)
    CheckBox ck_wxp;//危险品
    @Bind(R.id.ck_jyp)
    CheckBox ck_jyp;//禁用品
    @Bind(R.id.rg_goods_type)
    RadioGroup rg_goods_type;//贵重类型
    @Bind(R.id.rb_precious)
    RadioButton rb_precious;//贵重类型:贵重
    @Bind(R.id.rb_normal)
    RadioButton rb_normal;//贵重类型:一般
    @Bind(R.id.iv_pic)
    ImageView iv_pic;//要上传的图片（用户自己拍摄的）
    @Bind(R.id.spinner_goods_type)
    Spinner spinner_goods_type;//货物类型的spinner
    @Bind(R.id.btn_submit)
    Button btn_submit;//提交信息

    private static final int REQUEST_CODE_IV_ADD = 3;//拍照的回调码
    private boolean is_showing = false;//省市县的弹出框是否正在显示

    private String valuable_type = "0";//贵重类型
    private PoiWS ws;
    private CropParams mCropParams = new CropParams();
    public CustomDao customDao;
    public OrderDao orderDao;
    public GoodsTypeDao goodsTypeDao;
    private OrderBean orderBean;
    private List<CustomBean> person_list = null;

    private String latitude, longitude;
    private LocationManagerProxy aMapLocManager = null;
    private AMapLocation aMapLocation;// 用于判断定位超时
    private Handler handler = new Handler();
    private boolean isTask = false;
    private boolean isLocation = false;
    private String hwlx = "", hwlxbm = "", province = "", city = "", county = "", imgString = "";
    private int checkedProvinceId;
    private int checkedCityId;
    private int checkedCountyId;
    //=======================sdk====
    public int RESULT_GET_CARD_OK = 2;
    private TengineID tengineID = TengineID.TIDCARD2;
    OCRFORBITMAP ocrforbitmap = new OCRFORBITMAP();
    OCRFORPATH ocrforpath = new OCRFORPATH();

    /* 拍照的照片存储位置 */
    public static final File PHOTO_DIR = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Richbond");
    public static final String PHOTO_NAME = "sdwl.jpg";
    private File mCurrentPhotoFile;// 照相机拍照得到的图片
    //=======================wentong====
    private String devcode = "5RMW5Y2X552A6YK";//项目授权开发码
    private AuthService.authBinder authBinder;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final View view = setBaseContentLayout(R.layout.fragment_home);
        ButterKnife.bind(this, view);

        orderDao = new OrderDao(getActivity());
        customDao = new CustomDao(getActivity());
        goodsTypeDao = new GoodsTypeDao(getActivity());
        orderBean = new OrderBean();
        ws = new PoiWS(getActivity());

        tv_ssx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SystemUtil.closeSoftKeyboard(getActivity(), et_number);
                SystemUtil.closeSoftKeyboard(getActivity(), etRPhone);
                SystemUtil.closeSoftKeyboard(getActivity(), etPhone);
                SystemUtil.closeSoftKeyboard(getActivity(), etName);
                SystemUtil.closeSoftKeyboard(getActivity(), etIdCard);
                SystemUtil.closeSoftKeyboard(getActivity(), et_details_address);
                showPopwindow();
            }
        });
        //ck_kxys.setOnCheckedChangeListener();
        //设置贵重类型监听事件
        rg_goods_type.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                //获取变更后的选中项的ID
                int radioButtonId = group.getCheckedRadioButtonId();
                //根据ID获取RadioButton的实例
                RadioButton rb = (RadioButton) view.findViewById(radioButtonId);
                //更新文本内容，以符合选中项
                valuable_type = (rb.getText().toString()).equals("一般") ? "0" : "1";
            }
        });
        iv_pic.setVisibility(View.GONE);
        initProvinceDatas();//加载省市区数据

        /*//客户自定义界面下， 调用识别引擎的代码演示 开始
        //1. 通过路径进行识别, 具体代码参考OCRFORBITMAP，试用情况是拍照情况下，获取到的byte[]转成Bitmap进行识别
        String pathString = getImageFromSDcard("1.jpg"); // 演示图片放在SD卡目录下1.jpg
        ocrforpath.OCRFORPATH(pathString);
        //2. 通过Bitmap进行识别, 具体代码参考OCRFORBITMAP， Bitmap 必须是565格式的
        File file = new File(getImageFromSDcard("1.jpg"));
        if(file.exists())
        {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            Bitmap bitmap565 = BitmapFactory.decodeFile(pathString,options);
            ocrforbitmap.OCRForBitMap565(bitmap565);
        }
        TStatus tStatus = engineDemo.TR_StartUP();
        if (tStatus == TStatus.TR_TIME_OUT ) {
            DialogHelper.showToast(getActivity(), "引擎过期");

        }
        else  if (tStatus == TStatus.TR_FAIL) {
            DialogHelper.showToast(getActivity(), "引擎初始化失败");

        }*/
        TRCardScan.SetEngineType(TengineID.TIDCARD2);
        //自动填写信息，根据用户输入的手机号码，当输入到11位，自动查找寄件人信息。
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (etPhone.getText().length() == 11) {
                    person_list = null;
                    person_list = customDao.findDataByWord(etPhone.getText().toString());
                    if (person_list.size() > 0) {
                        etName.setText(person_list.get(0).getName());
                        etIdCard.setText(person_list.get(0).getIdcard());
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    /**
     * 初始化下拉框spinner
     *
     * @param list
     */
    private void initSpinner(final List<HwlxBean> list) {
        ArrayAdapter<HwlxBean> arr_adapter = new ArrayAdapter<HwlxBean>(getActivity(), android.R.layout.simple_spinner_dropdown_item, list);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner_goods_type.setAdapter(arr_adapter);
        spinner_goods_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                hwlx = ((HwlxBean) spinner_goods_type.getSelectedItem()).getMc();
                hwlxbm = ((HwlxBean) spinner_goods_type.getSelectedItem()).getDm();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @OnClick({R.id.iv_number, R.id.iv_id_card, R.id.btn_submit, R.id.ivAdd, R.id.iv_pic})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_number://打开扫描条码/二维码
                Intent intent = new Intent(getActivity(), CaptureActivity.class);
                startActivityForResult(intent, 0);
                break;
            case R.id.iv_id_card://打开身份证扫描
                Intent intent1 = new Intent(getActivity(), CameraActivity.class);
                intent1.putExtra("nMainId", SharedPreferencesHelper.getInt(getActivity().getApplicationContext(), "nMainId", 2));
                intent1.putExtra("devcode", devcode);
                startActivityForResult(intent1, 77);
                break;
            case R.id.iv_pic://点击用户拍好的图片
                showPicture();
                break;
            case R.id.ivAdd://打开照相机
                String status = Environment.getExternalStorageState();
                if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
                    doTakePhoto();// 用户点击了从照相机获取
                } else {
                    DialogHelper.showToast(getActivity(), "没有SD卡");
                }
                break;
            case R.id.btn_submit://提交内容
                String isLogin = UserSharedPreferences.find(getActivity()).getIsLogin();
                if (isLogin.equalsIgnoreCase("1")) {
                    orderBean.setUserid(MainActivity.s_userID);
                    orderBean.setPhone(MainActivity.s_userPhone);
                    orderBean.setBarcode(et_number.getText().toString());
                    orderBean.setCustomphone(etPhone.getText().toString());
                    orderBean.setCustomname(etName.getText().toString());
                    orderBean.setCustomcard(etIdCard.getText().toString());
                    orderBean.setLat(latitude);
                    orderBean.setLng(longitude);
                    orderBean.setHwlx(hwlx);
                    orderBean.setHwlxbm(hwlxbm);
                    orderBean.setRphone(etRPhone.getText().toString());
                    orderBean.setPhoto_a(imgString);
                    orderBean.setStatus("no");
                    orderBean.setArriveprovince(tv_ssx.getText().toString());
                    orderBean.setProvince(province);
                    orderBean.setCity(city);
                    orderBean.setCounty(county);
                    orderBean.setAddress(et_details_address.getText().toString());
                    orderBean.setIskxys(ck_kxys.isChecked() ? "1" : "0");
                    orderBean.setIswxp(ck_wxp.isChecked() ? "1" : "0");
                    orderBean.setIswjp(ck_jyp.isChecked() ? "1" : "0");
                    orderBean.setGzlx(valuable_type);
                    orderBean.setAppversion(SystemUtil.getVersionCode(getActivity()));
                    if (isTask) {
                        return;
                    }
                    if (StringUtils.isEmpty(orderBean.getHwlxbm())) {
                        DialogHelper.showToast(getActivity(), "您没有填写货物类型，无法提交");
                        return;
                    }
                    if (StringUtils.isEmpty(orderBean.getBarcode())) {
                        setErrorTip("请填写货物单号", et_number);
                        return;
                    }
                    if (StringUtils.isEmpty(orderBean.getRphone()) || orderBean.getRphone().length() != 11) {
                        setErrorTip("请填写正确收件人手机号码", etRPhone);
                        return;
                    }
                    if (StringUtils.isEmpty(orderBean.getCustomphone()) || orderBean.getCustomphone().length() != 11) {
                        setErrorTip("请填写正确寄件人手机号码", etPhone);
                        return;
                    }
                    if (StringUtils.isEmpty(orderBean.getCustomname()) || orderBean.getCustomname().length() < 2) {
                        setErrorTip("请填写正确用户姓名", etName);
                        return;
                    }
                    if (StringUtils.isEmpty(orderBean.getCustomcard()) || (orderBean.getCustomcard().length() != 15 && orderBean.getCustomcard().length() != 18)) {
                        setErrorTip("请填写正确用户身份证号码", etIdCard);
                        return;
                    }
                    if (StringUtils.isEmpty(orderBean.getArriveprovince())) {
                        DialogHelper.showToast(getActivity(), "请选择货物到站的省市区");
                        return;
                    }
                    if (StringUtils.isEmpty(orderBean.getAddress())) {
                        setErrorTip("请填写货物到站详细地址", et_details_address);
                        return;
                    }
                    saveCustom(orderBean);
                    if (UIHelp.isNetworkConnected(getActivity())) {
                        isTask = true;
                        new UpdateTask().execute();
                    } else {
                        DialogHelper.showToast(getActivity(), "网络异常，已将快件单保存至 “未提交快递” !");
                        if (orderDao.insertData(orderBean)) {
                            clearContent();
                        }
                    }
                } else {
                    DialogHelper.showToast(getActivity(), "登录后才能提交！");
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            openActivity(UserLoginActivity.class, null);//延时一秒跳转至登录界面
                        }
                    }, 500);
                }
                break;
        }
    }

    /**
     * 将图片用在另一个界面用大图显示
     */
    private void showPicture() {
        Log.v(TAG, "展示图片showPicture");
        Intent intent = new Intent(getActivity(), ShowPicActivity.class);
        startActivityForResult(intent, ShowPicActivity.RESULT_CODE_PIC);
    }

    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;
    private Button mBtnConfirm;

    private void setUpViews(View view) {
        mViewProvince = (WheelView) view.findViewById(R.id.id_province);
        mViewCity = (WheelView) view.findViewById(R.id.id_city);
        mViewDistrict = (WheelView) view.findViewById(R.id.id_district);
        mBtnConfirm = (Button) view.findViewById(R.id.btn_popwindow_submit);
    }

    private void setUpListener() {
        // 添加change事件
        mViewProvince.addChangingListener(this);
        // 添加change事件
        mViewCity.addChangingListener(this);
        // 添加change事件
        mViewDistrict.addChangingListener(this);
        // 添加onclick事件
        mBtnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
    }

    private void setUpData() {
        //initProvinceDatas();
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(getActivity(), mProvinceDatas));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        mViewDistrict.setVisibleItems(7);
        if (provinceId == -1) {
            mViewProvince.setCurrentItem(0);
        } else {
            mViewProvince.setCurrentItem(provinceId);
        }
        updateCities();
        updateAreas();
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if (wheel == mViewProvince) {
            Log.v(TAG, "省控件变化");
            updateCities();
            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[mViewDistrict.getCurrentItem()];
        } else if (wheel == mViewCity) {
            Log.v(TAG, "市控件变化");
            updateAreas();
            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[mViewDistrict.getCurrentItem()];
        } else if (wheel == mViewDistrict) {
            Log.v(TAG, "区控件变化");
            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
            mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
        }
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
        String[] areas = mDistrictDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[]{""};
        }
        mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(getActivity(), areas));
        if (countyId == -1) {
            mViewDistrict.setCurrentItem(0);
        } else {
            if (areas.length - 1 >= countyId) {
                mViewDistrict.setCurrentItem(countyId);
            } else {
                countyId = 0;
                mViewDistrict.setCurrentItem(0);
            }
        }
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[]{""};
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(getActivity(), cities));

        if (cityId == -1) {
            mViewCity.setCurrentItem(0);
        } else {
            if (cities.length - 1 >= cityId) {
                mViewCity.setCurrentItem(cityId);
            } else {
                cityId = 0;
                mViewCity.setCurrentItem(0);
            }
        }
        updateAreas();
    }

    private int provinceId;
    private int cityId;
    private int countyId;

    /**
     * 显示popupWindow
     */
    private void showPopwindow() {
        if (is_showing) {
            return;
        }
        is_showing = true;
        // 利用layoutInflater获得View
        LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.ssx_pop_window, null);

        // 下面是两种方法得到宽度和高度 getWindow().getDecorView().getWidth()
        final PopupWindow window = new PopupWindow(view,
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        // 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
        window.setFocusable(true);

        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        window.setBackgroundDrawable(dw);

        // 设置popWindow的显示和消失动画
        window.setAnimationStyle(R.style.mypopwindow_anim_style);
        // 在底部显示
        window.showAtLocation(getActivity().findViewById(R.id.tv_ssx), Gravity.BOTTOM, 0, 0);
        // 这里检验popWindow里的button是否可以点击
        setUpViews(view);
        setUpListener();
        setUpData();
        Button commit = (Button) view.findViewById(R.id.btn_popwindow_submit);
        Button cancel = (Button) view.findViewById(R.id.btn_popwindow_cancel);
        commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                province = mCurrentProviceName;
                city = mCurrentCityName;
                county = mCurrentDistrictName;

                checkedProvinceId = mViewProvince.getCurrentItem();//这三个id主要是保存用户点击确认时的id 为了回读用户选择
                checkedCityId = mViewCity.getCurrentItem();
                checkedCountyId = mViewDistrict.getCurrentItem();
                Log.v(TAG, "一共的省有：" + mProvinceDatas.length + "个");
                Log.v(TAG, "一共的市有：" + mCitisDatasMap.size() + "个");
                Log.v(TAG, "一共的区有：" + mDistrictDatasMap.size() + "个");
                tv_ssx.setText(province + " " + city + " " + county);
                window.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                window.dismiss();
            }
        });
        //popWindow消失监听方法
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                System.out.println("popWindow消失");
                provinceId = checkedProvinceId;//获取到用户确认选择的id popWindow显示时 回读此id
                cityId = checkedCityId;
                countyId = checkedCountyId;
                is_showing = false;
            }
        });
    }

    public void getLocation() {
        aMapLocManager = LocationManagerProxy.getInstance(getActivity());
        aMapLocManager.requestLocationData(LocationProviderProxy.AMapNetwork, 2000, 10, this);
        handler.postDelayed(this, 6000);// 设置超过6秒还没有定位到就停止定位
    }

    protected void stopLocation() {
        if (aMapLocManager != null) {
            aMapLocManager.removeUpdates(this);
            aMapLocManager.destroy();
        }
        aMapLocManager = null;
        isLocation = false;
    }

    /**
     * 每次该界面唤醒别调用
     */
    @Override
    public void onResume() {
        super.onResume();
        initSpinner(HwlxSharedPreferences.find(getActivity()));
        if (UIHelp.isNetworkConnected(getActivity())) {
            new GetContentsTask().execute();
        }
        /*if (pic_flag) {
            pic_flag = false;
            Bitmap imageBitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + CropHelper.CROP_CACHE_FILE_NAME);
            setImg(imageBitmap);//从路径中获取bitmap
        }*/
    }

    //回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.v(TAG, "requestCode=" + requestCode + "resultCode=" + resultCode);
        if (requestCode == ShowPicActivity.RESULT_CODE_PIC) {
            Log.v(TAG, "删除图片");
            if (data != null) {
                if (data.getStringExtra("flag").equals("delete")) {
                    DialogHelper.showToast(getActivity(), "删除成功，您可以重新添加照片");
                    imgString = "";
                    iv_pic.setVisibility(View.GONE);
                }
            }
        } else if (resultCode == 88) {
            if (data != null) {
                if (requestCode == 0) {//扫描物流单号
                    Bundle bundle = data.getExtras();
                    String scanResult = bundle.getString("result");
                    et_number.setText(scanResult);
                } else if (requestCode == 77) {//扫描身份证号码
                    Bundle bundle = data.getExtras();
                    String sendName = bundle.getString("sendName");
                    String sendIdCard = bundle.getString("sendIdCard");
                    etIdCard.setText(sendIdCard);
                    etName.setText(sendName);
                }
            }
        } else if (resultCode == -2) {
            Toast.makeText(getActivity(), "未能识别,请您重新扫描！", Toast.LENGTH_LONG).show();
        } else if (requestCode == RESULT_GET_CARD_OK) {
            if (data != null) {
                CardInfo cardInfo = (CardInfo) data.getSerializableExtra("cardinfo");
                etIdCard.setText(cardInfo.getFieldString(TFieldID.NUM));
                etName.setText(cardInfo.getFieldString(TFieldID.NAME));
            }
        } else if (requestCode == REQUEST_CODE_IV_ADD) {
            if (resultCode == 0) {
                return;
            }
            Bitmap bitmap = ImageUtil.decodeFile(mCurrentPhotoFile);
            setImg(bitmap);
        }
        /* else if (requestCode == CropHelper.REQUEST_CROP) {//裁剪好的 (经测试，这里没有被调用，而是在HomeFragment的父Activity中被截取了
            //在这边写了一个标记 那边被调用 就修改标记 HomeFragment这边的onResume方法中判断标记 )
            Bitmap bitmap = null;
            bitmap = CropHelper.decodeUriAsBitmap(getActivity(), mCropParams.uri);
            if (bitmap != null) {
                Log.v(TAG, "onPhotoCropped：bitmap bu为空");
                setImg(bitmap);
            } else {
                Log.v(TAG, "onPhotoCropped：bitmap为空");
                Toast.makeText(getActivity(), "请选择图库的图片!", Toast.LENGTH_LONG).show();
            }
        }//拍摄物流照片的回调
        else if (requestCode == CropHelper.REQUEST_CAMERA) {
            Log.v(TAG, "拍摄物流照片的回调");
            Bitmap imageBitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + CropHelper.CROP_CACHE_FILE_NAME);
            setImg(imageBitmap);//从路径中获取bitmap

            *//*CropHelper.handleResult(new CropHandler() {
                @Override
                public void onPhotoCropped(Uri uri) {
                    Bitmap bitmap = null;
                    bitmap = CropHelper.decodeUriAsBitmap(getActivity(), mCropParams.uri);
                    if (bitmap != null) {
                        Log.v(TAG, "onPhotoCropped：bitmap bu为空");
                        setImg(bitmap);
                    } else {
                        Log.v(TAG, "onPhotoCropped：bitmap 为空");
                    }
                }

                @Override
                public void onCropCancel() {
                    Log.v(TAG, "onCropCancel");
                }

                @Override
                public void onCropFailed(String message) {
                    Toast.makeText(getActivity(), "Crop failed:" + message, Toast.LENGTH_LONG).show();
                }

                @Override
                public CropParams getCropParams() {
                    return mCropParams;
                }

                @Override
                public Activity getContext() {
                    return getActivity();
                }

                @Override
                public void goResult(Intent intent) {
                    startActivityForResult(intent, CropHelper.REQUEST_CROP);
                }
            }, requestCode, resultCode, data);*//*
        }*/
    }

    /**
     * 拍照获取图片
     */
    /*protected void doTakePhoto() {
        Intent intent = CropHelper.buildCaptureIntent(mCropParams.uri);
        startActivityForResult(intent, CropHelper.REQUEST_CAMERA);
    }*/

    /**
     * 拍照获取图片
     */
    protected void doTakePhoto() {
        try {
            PHOTO_DIR.mkdirs();// 创建照片的存储目录
            mCurrentPhotoFile = new File(PHOTO_DIR, PHOTO_NAME);// 给新照的照片文件命名
            if (!mCurrentPhotoFile.exists()) {
                try {
                    mCurrentPhotoFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCurrentPhotoFile));
            intent.putExtra("return-data", false);
            startActivityForResult(intent, REQUEST_CODE_IV_ADD);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(getActivity(), "无法启用拍照功能", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 展示出用户拍的照片
     *
     * @param bitmap
     */
    private void setImg(Bitmap bitmap) {
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 95, bao);
        byte[] ba = bao.toByteArray();
        imgString = Base64.encodeBytes(ba);
        Log.v(TAG, "imgString的长度为：" + imgString.length());
        iv_pic.setImageBitmap(bitmap);
        iv_pic.setVisibility(View.VISIBLE);
    }

    /**
     * 百度地图定位
     *
     * @param aMapLocation
     */
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            this.aMapLocation = aMapLocation;// 判断超时机制
            Double geoLat = aMapLocation.getLatitude();
            Double geoLng = aMapLocation.getLongitude();
            latitude = String.valueOf(geoLat);
            longitude = String.valueOf(geoLng);
            orderBean.setLat(latitude);
            orderBean.setLng(longitude);
            Log.e("latitude====", latitude);
            Log.e("longitude===", longitude);
            if (isLocation) {
                return;
            }
            isLocation = true;
            Log.v(TAG, "SendInfo--------" + orderBean.toString());
            new SendInfo().execute(orderBean);
        }
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void run() {
        if (aMapLocation == null) {
            DialogHelper.showToast(getActivity(), "获取定位失败,请重新提交!");
            stopLocation();// 销毁掉定位
            isTask = false;
        } else {
            stopLocation();// 销毁掉定位
        }
    }

    /**
     * 清除输入框内容
     */
    private void clearContent() {
        spinner_goods_type.setSelection(0);
        et_number.setText("");
        etRPhone.setText("");
        etPhone.setText("");
        etName.setText("");
        etIdCard.setText("");
        tv_ssx.setText("");
        et_details_address.setText("");
        ck_kxys.setChecked(false);
        ck_jyp.setChecked(false);
        ck_wxp.setChecked(false);
        rb_normal.setChecked(true);
        imgString = "";
        iv_pic.setVisibility(View.GONE);
    }

    /**
     * 寄件人信息的保存。先判断该寄件人信息是否存在，存在即删除，然后再添加新的信息
     *
     * @param orderBean
     */
    public void saveCustom(OrderBean orderBean) {
        if (customDao.findData().size() > 0) {
            customDao.deleteByPhone(orderBean.getCustomphone());
        }
        CustomBean customBean = new CustomBean();
        customBean.setPhone(orderBean.getCustomphone());
        customBean.setName(orderBean.getCustomname());
        customBean.setIdcard(orderBean.getCustomcard());
        customDao.insertData(customBean);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    /**
     * 获取更新的异步任务
     */
    private class UpdateTask extends AsyncTask<String, String, JSONObject> {
        @Override
        protected JSONObject doInBackground(String... params) {
            return ws.Update();
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            super.onPostExecute(result);
            Log.v("获取更新的json---result=======", String.valueOf(result));
            if (JsonUtil.GetJsonStatu(result)) {
                final UpdateBean updateBean = new UpdateBean();
                try {
                    JSONObject jsonObject = result.getJSONObject("data");
                    updateBean.setAppVersionCode(jsonObject.getString("appVersionCode"));
                    updateBean.setAppVersionName(jsonObject.getString("appVersionName"));
                    updateBean.setAppDownloadUrl(jsonObject.getString("appDownloadUrl"));
                    updateBean.setWebInterface(jsonObject.getString("webInterface"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                UpdateManager manager = new UpdateManager(getActivity(), updateBean);
                if (manager.isUpdate()) {
                    DialogHelper.closeProgressDialog();
                    btn_submit.setClickable(true);
                    // 显示提示对话框
                    DialogHelper.showToast(getActivity(), "请在设置中更新到最新版本,否则无法使用!");
                    isTask = false;
                } else {
                    getLocation();
                }
            } else {
                DialogHelper.showToast(getActivity(), JsonUtil.GetString(result, "msg"));
                DialogHelper.closeProgressDialog();
            }
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            DialogHelper.showProgressDialog(getActivity(), "正在提交...");
            btn_submit.setClickable(false);
        }
    }

    /**
     * 提交录入的信息
     */
    class SendInfo extends AsyncTask<OrderBean, String, JSONObject> {

        @Override
        protected JSONObject doInBackground(OrderBean... params) {
            return ws.sendInfo(params[0]);
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            super.onPostExecute(result);
            btn_submit.setClickable(true);
            Log.i("SendInfo=======", String.valueOf(result));
            isTask = false;
            if (JsonUtil.GetJsonStatu(result)) {
                orderDao.insertData(orderBean);
                //提交成功，修改快递单状态
                if (orderDao.updateStatus(et_number.getText().toString(), OrderDao.STATUS_YES)) {
                    clearContent();
                }
                //clearContent();//清除文本框
                DialogHelper.showToast(getActivity(), "已提交成功！");
            } else {
                DialogHelper.showToast(getActivity(), JsonUtil.GetString(result, "msg"));
            }
            DialogHelper.closeProgressDialog();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
    }

    /**
     * 获取货物类型列表
     */
    class GetContentsTask extends AsyncTask<String, String, JSONObject> {

        @Override
        protected JSONObject doInBackground(String... params) {
            return ws.getContents(MainActivity.s_userPhone);
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            super.onPostExecute(result);
            Log.i("GetContentsTask=======", String.valueOf(result));
            isTask = false;
            if (JsonUtil.GetJsonStatu(result)) {
                JSONArray jsArray = null;
                try {
                    jsArray = result.getJSONArray("data");
                    HwlxSharedPreferences.add(jsArray.toString(), getActivity());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}